// pages\expertPath\expertConversation\expertConversation.js
const app = getApp();
// 引入模拟数据
const mockData = require('../../../utils/mockData.js');

Page({
  data: {
    pathID: '',
    unionID: '',
    messages: [],
    inputValue: '',
    showPathPopup: false,
    conversationTitle: '',
    learningPath: [],
    masteryStatus: {}, 
    isLoading: false,
    showHintPopup: false,
    scrollToMessageId: '',
    showAllQuestionsPopup: false,
    userRole: '',
    estimatedTime: 30,
    subject: '',
    subjectDisplay: '', 
    remainingDailyToken: 0,
    remainingTotalToken: 0
  },

  onLoad(options) {
    console.time('expertConversation onLoad');
    const { pathID, inviterID } = options;
    const unionID = inviterID || wx.getStorageSync('unionID') || '';
    const jwtToken = wx.getStorageSync('jwt_token') || '';
    const userRole = app.globalData.userInfo?.role || wx.getStorageSync('role') || 'lifelong_learner';
  
    console.log('expertConversation onLoad options:', { pathID, inviterID, unionID, userRole });
  
    // 验证 pathID 是否有效
    if (!pathID || !pathID.startsWith('expert')) {
      console.error('无效的 pathID:', pathID);
      wx.showToast({ title: '无效的学习路径', icon: 'none' });
      wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
      return;
    }
  
    // 设置缓存
    wx.setStorageSync('lastPage', 'expertConversation');
    wx.setStorageSync('selectedConversationID', pathID);
  
    if (!jwtToken || !unionID) {
      wx.showModal({
        title: '提示',
        content: '请登录以查看学习路径',
        success: (res) => {
          if (res.confirm) {
            wx.redirectTo({
              url: `/pages/login/login?redirect=/pages/expertPath/expertConversation/expertConversation?pathID=${pathID}&inviterID=${unionID}`
            });
          } else {
            wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
          }
        }
      });
      return;
    }
  
    this.setData({
      pathID,
      unionID,
      userRole,
      showPathPopup: true
    });
  
    this.loadPathDetail();
    this.loadMessages();
    console.timeEnd('expertConversation onLoad');
  },
  
  loadPathDetail() {
    console.time('loadPathDetail MOCK');
    wx.showLoading({ title: '加载中...' });
    
    // 使用模拟数据
    setTimeout(() => {
      wx.hideLoading();
      console.timeEnd('loadPathDetail MOCK');
      
      const expertPaths = mockData['conversation.expert_path'] || [];
      const currentPath = expertPaths.find(path => path.pathID === this.data.pathID) || expertPaths[0];
      
      if (currentPath) {
        const { goal, subject, path } = currentPath;
        const cleanedPath = path.map(item => item.trim());
        const cleanedMasteryStatus = {};
        
        // 创建模拟的掌握状态
        cleanedPath.forEach((item, index) => {
          if (index < 3) {
            cleanedMasteryStatus[item.trim()] = 'mastered';
          } else if (index < 6) {
            cleanedMasteryStatus[item.trim()] = 'learning';
          } else {
            cleanedMasteryStatus[item.trim()] = 'not_started';
          }
        });
        
        this.setData({
          conversationTitle: goal,
          subject: subject || 'general',
          subjectDisplay: this.getSubjectDisplay(subject || 'general'),
          learningPath: cleanedPath,
          masteryStatus: cleanedMasteryStatus,
          showPathPopup: false
        }, () => {
          this.setData({ showPathPopup: true });
        });
      } else {
        wx.showToast({ title: '暂无学习路径数据', icon: 'none' });
        wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
      }
    }, 500); // 模拟网络延迟
  },
  
  loadMessages() {
    console.time('loadMessages MOCK');
    
    // 使用模拟数据
    setTimeout(() => {
      console.timeEnd('loadMessages MOCK');
      
      const messages = mockData['conversation.message'] || [];
      const formattedMessages = messages.map(msg => ({
        messageID: msg._id?.$oid || `mock_${Date.now()}_${Math.random()}`,
        question: msg.question,
        answer: msg.answer,
        whyItMatters: msg.prompts?.whyItMatters || '',
        stopAndThink: msg.prompts?.stopAndThink || '',
        misconception: msg.misconception || '',
        testQuestions: msg.testQuestions ? msg.testQuestions.map(tq => ({
          stem: tq.stem || '',
          options: tq.options || [],
          correctAnswer: tq.correctAnswer || '',
          explanation: tq.explanation || '',
          selectedOption: '',
          resultStatus: '',
          feedback: ''
        })) : [],
        interactiveList: msg.interactiveList || [],
        recommendedQuestions: msg.recommendedQuestions || []
      }));
      
      const uniqueMessages = [];
      const seenQuestions = new Set();
      for (const msg of formattedMessages) {
        const normalizedQuestion = msg.question.trim().toLowerCase();
        if (!seenQuestions.has(normalizedQuestion)) {
          seenQuestions.add(normalizedQuestion);
          uniqueMessages.push(msg);
        } else {
          console.warn(`忽略重复消息: ${msg.question}`);
        }
      }
      
      this.setData({ messages: uniqueMessages });
      if (uniqueMessages.length > 0) {
        this.scrollToFirstMessage();
      }
    }, 300); // 模拟网络延迟
  },
  
  onShow() {
    // 更新 lastPage 和 selectedConversationID
    wx.setStorageSync('lastPage', 'expertConversation');
    if (this.data.pathID) {
      wx.setStorageSync('selectedConversationID', this.data.pathID);
    }
    console.log('expertConversation onShow:', { pathID: this.data.pathID, lastPage: wx.getStorageSync('lastPage') });
  },

  scrollToFirstMessage() {
    setTimeout(() => {
      if (this.data.messages.length > 0) {
        this.setData({ scrollToMessageId: 'message-0' });
      }
    }, 300);
  },

  showPathPopup() {
    if (this.data.learningPath.length > 0) {
      this.setData({ showPathPopup: true });
    }
  },

  hidePathPopup() {
    this.setData({ showPathPopup: false });
  },

  onPathItemClick(e) {
    const { item } = e.currentTarget.dataset;
    const normalizedItem = item.trim().toLowerCase();
    const existingMessageIndex = this.data.messages.findIndex(msg => 
      msg.question.trim().toLowerCase() === normalizedItem
    );

    if (existingMessageIndex !== -1) {
      console.log(`已有消息: ${item}, 滚动到索引 ${existingMessageIndex}`);
      this.scrollToExistingMessage(existingMessageIndex);
      this.setData({ showPathPopup: false, isLoading: false });
      return;
    }

    this.setData({ isLoading: true });
    
    // 使用模拟数据
    setTimeout(() => {
      this.setData({ isLoading: false });
      
      // 从模拟数据中查找匹配的消息
      const mockMessages = mockData['conversation.message'] || [];
      const matchedMessage = mockMessages.find(msg => 
        msg.question.trim().toLowerCase() === normalizedItem
      );
      
      if (matchedMessage) {
        const newMessage = {
          messageID: matchedMessage._id?.$oid || `mock_${Date.now()}_${Math.random()}`,
          question: item,
          answer: matchedMessage.answer,
          whyItMatters: matchedMessage.prompts?.whyItMatters || '',
          stopAndThink: matchedMessage.prompts?.stopAndThink || '',
          misconception: matchedMessage.misconception || '',
          testQuestions: matchedMessage.testQuestions ? matchedMessage.testQuestions.map(tq => ({
            stem: tq.stem || '',
            options: tq.options || [],
            correctAnswer: tq.correctAnswer || '',
            explanation: tq.explanation || '',
            selectedOption: '',
            resultStatus: '',
            feedback: ''
          })) : [],
          interactiveList: matchedMessage.interactiveList || [],
          recommendedQuestions: matchedMessage.recommendedQuestions || []
        };
        
        const normalizedQuestion = newMessage.question.trim().toLowerCase();
        if (this.data.messages.some(msg => msg.question.trim().toLowerCase() === normalizedQuestion)) {
          console.log(`忽略重复添加: ${newMessage.question}`);
          this.scrollToExistingMessage(
            this.data.messages.findIndex(msg => msg.question.trim().toLowerCase() === normalizedQuestion)
          );
          this.setData({ showPathPopup: false });
          return;
        }
        
        const updatedMessages = [...this.data.messages, newMessage];
        this.setData({ 
          messages: updatedMessages, 
          showPathPopup: false,
          remainingDailyToken: 95, // 模拟剩余令牌
          remainingTotalToken: 495 // 模拟剩余令牌
        });
        this.scrollToNewMessage(updatedMessages.length - 1);
      } else {
        console.error('未找到匹配的消息:', item);
        wx.showToast({ title: '该知识点暂无内容', icon: 'none' });
      }
    }, 500); // 模拟网络延迟
  },

  sendMessage() {
    const input = this.data.inputValue.trim();
    if (!input) {
      wx.showToast({ title: '请输入内容', icon: 'none' });
      return;
    }
    this.handleQuestion(input);
    this.setData({ inputValue: '' });
  },

  handleInput(e) {
    this.setData({ inputValue: e.detail.value });
  },

  handleQuestion(question, isInteractive = false) {
    const normalizedQuestion = question.trim().toLowerCase();
    const existingMessageIndex = this.data.messages.findIndex(msg => 
      msg.question.trim().toLowerCase() === normalizedQuestion
    );
  
    if (existingMessageIndex !== -1) {
      console.log(`已有消息: ${question}, 滚动到索引 ${existingMessageIndex}`);
      this.scrollToExistingMessage(existingMessageIndex);
      return;
    }
    this.sendToServer(question, isInteractive);
  },
  
  sendToServer(question, isInteractive = false) {
    this.setData({ isLoading: true });
  
    const cleanItem = isInteractive
      ? question.replace(/[^a-zA-Z0-9\u4e00-\u9fff\s,.;:\-\+\*/=()（）《》·]/g, '')
      : question;
  
    if (isInteractive && !cleanItem.trim()) {
      this.setData({ isLoading: false });
      wx.showModal({
        title: '提示',
        content: '知识点内容无效，请尝试其他知识点',
        confirmText: '好的',
        showCancel: false
      });
      return;
    }
  
    // 使用模拟数据
    setTimeout(() => {
      this.setData({ isLoading: false });
      
      // 从模拟数据中查找匹配的消息，如果没有则创建默认消息
      const mockMessages = mockData['conversation.message'] || [];
      const matchedMessage = mockMessages.find(msg => 
        msg.question.trim().toLowerCase() === cleanItem.trim().toLowerCase()
      );
      
      if (matchedMessage || !isInteractive) {
        const newMessage = matchedMessage ? {
          messageID: matchedMessage._id?.$oid || `mock_${Date.now()}_${Math.random()}`,
          question: question,
          answer: matchedMessage.answer,
          whyItMatters: matchedMessage.prompts?.whyItMatters || '',
          stopAndThink: matchedMessage.prompts?.stopAndThink || '',
          misconception: matchedMessage.misconception || '',
          testQuestions: matchedMessage.testQuestions ? matchedMessage.testQuestions.map(tq => ({
            stem: tq.stem || '',
            options: tq.options || [],
            correctAnswer: tq.correctAnswer || '',
            explanation: tq.explanation || '',
            selectedOption: '',
            resultStatus: '',
            feedback: ''
          })) : [],
          interactiveList: matchedMessage.interactiveList || [],
          recommendedQuestions: matchedMessage.recommendedQuestions || []
        } : {
          messageID: `mock_${Date.now()}_${Math.random()}`,
          question: question,
          answer: '这是模拟的回答内容。在实际环境中，AI会根据您的问题生成详细的解释和教学内容。',
          whyItMatters: '理解这个概念对后续学习非常重要。',
          stopAndThink: '请思考这个概念在实际中的应用。',
          misconception: '常见的误解是...',
          testQuestions: [],
          interactiveList: ['相关概念1', '相关概念2'],
          recommendedQuestions: ['相关问题1', '相关问题2']
        };
        
        const normalizedQuestion = newMessage.question.trim().toLowerCase();
        if (this.data.messages.some(msg => msg.question.trim().toLowerCase() === normalizedQuestion)) {
          console.log(`忽略重复添加: ${newMessage.question}`);
          this.scrollToExistingMessage(
            this.data.messages.findIndex(msg => msg.question.trim().toLowerCase() === normalizedQuestion)
          );
          return;
        }
        
        const updatedMessages = [...this.data.messages, newMessage];
        this.setData({
          messages: updatedMessages
        });
        this.scrollToNewMessage(updatedMessages.length - 1);
      } else {
        wx.showModal({
          title: '提示',
          content: '该知识点不在当前学习路径中，请选择学习路径中的知识点',
          confirmText: '好的',
          showCancel: false
        });
      }
    }, 500); // 模拟网络延迟
  },

  onTestOptionClick(e) {
    const { messageIndex, questionIndex, option } = e.currentTarget.dataset;
    const messages = this.data.messages;
    console.log('消息数据:', messages); // 调试消息数据
    const testQuestion = messages[messageIndex].testQuestions[questionIndex];
    const selectedOption = option.includes('.') ? option.split('.')[0].trim() : option.trim();
  
    // 检查是否已答正确，防止重复提交
    if (testQuestion.resultStatus === 'correct') {
      wx.showToast({ title: '已答正确，无法再次答题', icon: 'none' });
      return;
    }
  
    const isCorrect = selectedOption === testQuestion.correctAnswer;
    testQuestion.selectedOption = selectedOption;
    testQuestion.resultStatus = isCorrect ? 'correct' : 'incorrect';
    testQuestion.feedback = isCorrect ? '回答正确！' : '回答错误，请查看解析。';
  
    this.setData({
      [`messages[${messageIndex}].testQuestions[${questionIndex}]`]: testQuestion
    });
  
    // 提交测试结果（模拟）
    this.recordTestResult({
      messageIndex,
      questionIndex,
      selectedOption,
      isCorrect,
      messageID: messages[messageIndex].messageID,
      question: messages[messageIndex].question, // 使用消息的 question
      pathID: this.data.pathID
    });
  },
  
  recordTestResult({ messageIndex, questionIndex, selectedOption, isCorrect, messageID, question, pathID }) {
    const unionID = this.data.unionID;
  
    // 验证必填字段
    if (!unionID || !messageID || !question || !selectedOption || !pathID) {
      console.error('缺少必要参数:', { unionID, messageID, question, selectedOption, pathID });
      wx.showToast({ title: '用户信息或数据缺失', icon: 'none' });
      return;
    }
  
    console.log('提交测试数据（模拟）:', {
      unionID,
      messageID,
      question,
      selectedOption,
      isCorrect,
      pathID
    });
  
    // 模拟提交成功
    setTimeout(() => {
      console.log('测试结果提交成功（模拟）');
      wx.showToast({ title: '答题结果已记录', icon: 'success' });
      this.loadPathDetail(); // 刷新路径详情
    }, 300);
  },

  scrollToNewMessage(index) {
    setTimeout(() => {
      this.setData({ scrollToMessageId: `message-${index}` });
    }, 300);
  },

  scrollToExistingMessage(index) {
    setTimeout(() => {
      this.setData({ scrollToMessageId: `message-${index}` });
    }, 300);
  },

  onInteractiveItemClick(e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.handleQuestion(selectedItem, true); // 标记为交互项
  },
  
  onRecommendedQuestionClick(e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.handleQuestion(selectedItem, true); // 标记为推荐问题
  },

  hideHintPopup() {
    this.setData({ showHintPopup: false });
  },

  stopPropagation() {},

  showAllQuestionsPopup() {
    this.setData({ showAllQuestionsPopup: true });
  },

  hideAllQuestionsPopup() {
    this.setData({ showAllQuestionsPopup: false });
  },

  onQuestionItemClick(e) {
    const index = e.currentTarget.dataset.index;
    this.scrollToExistingMessage(index);
    this.hideAllQuestionsPopup();
  },

  getSubjectDisplay(subject) {
    return subject || '未知学科';
  },

  // 转发和分享的公共内容
  getShareConfig() {
    const title = this.data.conversationTitle || '学习导航';
    const pathID = this.data.pathID;
    const unionID = this.data.unionID || wx.getStorageSync('unionID') || '';
    const subjectDisplay = this.getSubjectDisplay(this.data.subject);
    return { title, pathID, unionID, subjectDisplay };
  },

  // 用户点击右上角菜单中的"转发"
  onShareAppMessage() {
    const { title, pathID, unionID, subjectDisplay } = this.getShareConfig();
    if (!pathID || !unionID) {
      console.warn('Missing pathID or unionID:', { pathID, unionID });
      return {
        title: `[${subjectDisplay}] ${title}`,
        path: '/pages/index/index'
      };
    }
    const path = `/pages/expertPath/expertConversation/expertConversation?pathID=${pathID}&inviterID=${unionID}`;
    return {
      title: `[${subjectDisplay}] ${title}`,
      path
    };
  },

  // 用户点击右上角菜单中的"分享到朋友圈"
  onShareTimeline() {
    const { title, pathID, unionID, subjectDisplay } = this.getShareConfig();
    if (!pathID || !unionID) {
      console.warn('Missing pathID or unionID:', { pathID, unionID });
      return {
        title: `[${subjectDisplay}] ${title}`,
        query: ''
      };
    }
    const query = `pathID=${pathID}&inviterID=${unionID}`;
    return {
      title: `[${subjectDisplay}] ${title}`,
      query
    };
  },
});